import React, { Component } from 'react';
import { Dimensions, StyleSheet, Text, TouchableOpacity } from 'react-native';

import CodePush from 'react-native-code-push';
import ViewUtils from '../util/ViewUtil';
import NavigationBar from 'react-native-navbar-plus';
import SafeAreaViewPlus from 'react-native-safe-area-plus';
import GlobalStyles from '../res/GlobalStyles';
import NavigationUtil from '../navigator/NavigationUtil';
import AnalyticsUtil from "../util/AnalyticsUtil";
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { restartAllowed: true };
  }

  codePushStatusDidChange(syncStatus) {
    switch (syncStatus) {
      case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
        this.setState({ syncMessage: '查询跟新包中......' });
        break;
      case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
        this.setState({ syncMessage: '安装包下载中......' });
        break;
      case CodePush.SyncStatus.AWAITING_USER_ACTION:
        this.setState({ syncMessage: '正在等待用户操作.' });
        break;
      case CodePush.SyncStatus.INSTALLING_UPDATE:
        this.setState({ syncMessage: '安装跟新中......' });
        break;
      case CodePush.SyncStatus.UP_TO_DATE:
        this.setState({ syncMessage: '已经是最新版本.', progress: false });
        break;
      case CodePush.SyncStatus.UPDATE_IGNORED:
        this.setState({
          syncMessage: '用户取消跟新.',
          progress: false,
        });
        break;
      case CodePush.SyncStatus.UPDATE_INSTALLED:
        this.setState({
          syncMessage: '跟新完成,正在重启',
          progress: false,
        });
        CodePush.restartApp(true);
        break;
      case CodePush.SyncStatus.UNKNOWN_ERROR:
        this.setState({
          syncMessage: '一个未知的错误.',
          progress: false,
        });
        break;
    }
  }

  codePushDownloadDidProgress(progress) {
    this.setState({ progress });
  }

  // toggleAllowRestart() {
  //   this.state.restartAllowed
  //     ? CodePush.disallowRestart()
  //     : CodePush.allowRestart();

  //   this.setState({ restartAllowed: !this.state.restartAllowed });
  // }

  getUpdateMetadata() {
    CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING).then(
      (metadata) => {
        this.setState({
          syncMessage: metadata
            ? JSON.stringify(metadata)
            : '运行二进制',
          progress: false,
        });
      },
      (error) => {
        this.setState({ syncMessage: 'Error: ' + error, progress: false });
      },
    );
  }

  /** Update is downloaded silently, and applied on restart (recommended) */
  sync() {
    AnalyticsUtil.onEvent('DetectionUpdate');
    CodePush.sync(
      {},
      this.codePushStatusDidChange.bind(this),
      this.codePushDownloadDidProgress.bind(this),
    );
  }

  /** Update pops a confirmation dialog, and then immediately reboots the app */
  syncImmediate() {
    CodePush.sync(
      { installMode: CodePush.InstallMode.IMMEDIATE, updateDialog: true },
      this.codePushStatusDidChange.bind(this),
      this.codePushDownloadDidProgress.bind(this),
    );
  }
  // isUpdateApp() {
  //   CodePush.checkForUpdate()
  //     .then((update) => {
  //       if (!update) {
  //         this.setState({ syncMessage: 'The app is up to date!' });
  //         // console.log("The app is up to date!");
  //       } else {
  //         // console.log("An update is available! Should we download it?");
  //         this.setState({ syncMessage: 'An update is available! Should we download it?' });
  //       }
  //     });
  // }
  render() {
    let progressView;

    if (this.state.progress) {
      progressView = (
        <Text style={styles.messages}>
          {this.state.progress.receivedBytes} /{' '}
          {this.state.progress.totalBytes} 接收字节
        </Text>
      );
    }
    const { theme } = this.props.route.params;
    return (
      <SafeAreaViewPlus
        style={GlobalStyles.root_container}
        topColor={theme.themeColor}>
        <NavigationBar
          style={theme.styles.navBar}
          leftButton={ViewUtils.getLeftBackButton(() =>
            NavigationUtil.goBack(this.props.navigation),
          )}
          title={'版本'}
        />
        <Text style={styles.welcome}>当前版本1.0.0</Text>
        <TouchableOpacity onPress={this.sync.bind(this)}>
          <Text style={styles.syncButton}>检测版本</Text>
        </TouchableOpacity>
        {/* 查询是否有可用跟新 */}
        {/* <TouchableOpacity onPress={this.isUpdateApp.bind(this)}>
          <Text style={styles.syncButton}>是否有可用跟新</Text>
        </TouchableOpacity> */}
        {/* <TouchableOpacity onPress={this.syncImmediate.bind(this)}>
          <Text style={styles.syncButton}>Press for dialog-driven sync</Text>
        </TouchableOpacity> */}
        {progressView}
        {/* <TouchableOpacity onPress={this.toggleAllowRestart.bind(this)}>
          <Text style={styles.restartToggleButton}>
            Restart {this.state.restartAllowed ? 'allowed' : 'forbidden'}
          </Text>
        </TouchableOpacity> */}
        <TouchableOpacity onPress={this.getUpdateMetadata.bind(this)}>
          <Text style={styles.syncButton}>跟新元数据</Text>
        </TouchableOpacity>
        <Text style={styles.messages}>{this.state.syncMessage || ''}</Text>
      </SafeAreaViewPlus>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  image: {
    margin: 30,
    width: Dimensions.get('window').width - 100,
    height: (365 * (Dimensions.get('window').width - 100)) / 651,
  },
  messages: {
    marginTop: 30,
    textAlign: 'center',
  },
  restartToggleButton: {
    color: 'blue',
    fontSize: 17,
  },
  syncButton: {
    color: 'green',
    fontSize: 17,
    textAlign:'center'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 20,
  },
});

/**
 * Configured with a MANUAL check frequency for easy testing. For production apps, it is recommended to configure a
 * different check frequency, such as ON_APP_START, for a 'hands-off' approach where CodePush.sync() does not
 * need to be explicitly called. All options of CodePush.sync() are also available in this decorator.
 */
let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };

App = CodePush(codePushOptions)(App);

export default App;
